package com.glodon.ggzy.core.servlet;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * 解决get方式提交乱码问题
 * @author zhangxj-a
 * @since jdk1.6
 * @date 2012-4-17
 *  
 */
public class GgzyEncodingFilter extends OncePerRequestFilter {

	private final Logger logger = LoggerFactory.getLogger(GgzyEncodingFilter.class.getName());

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException,
			IOException {
		request.setCharacterEncoding("UTF-8");

		HttpServletRequest httpServletRequest = request;

		ArrayList<String> queryValues = new ArrayList<String>();
		String query = httpServletRequest.getQueryString();
		if (query != null) {
			String[] expressions = query.split("&");
			for (String expression : expressions) {
				String[] parts = expression.split("=");
				if (parts.length == 2) {
					String str = URLDecoder.decode(parts[1], "UTF-8");
					queryValues.add(new String(str.getBytes("UTF-8"), "ISO-8859-1"));
					logger.info(" request get parameter query key : {},value : {}", new String[] { parts[0], str });
				}
			}
		}

		Collection values = request.getParameterMap().values();
		for (Iterator iterator = values.iterator(); iterator.hasNext();) {
			String[] strs = (String[]) iterator.next();

			for (int i = 0; i < strs.length; i++) {
				for (String qStr : queryValues) {
					if (qStr.equals(strs[i])) {
						strs[i] = new String(qStr.getBytes("ISO-8859-1"), "UTF-8");
						break;
					}
				}
			}
		}

		filterChain.doFilter(request, response);

	}
}
